//
//  WeatherAPI.swift
//  RunAPI
//
//  Created by mrsong on 2020/4/14.
//

import Foundation
import MSAPI

let weatherProvider = APIProvider<Weather>()

public class WeatherAPI {
    /// 缓存城市代码
    static var cityCodeCache: [String: String] = [:]
    
    /// Real-time weather information.
    /// - Parameters:
    ///   - cityName: City name.
    ///   - completion: Success will return instance of WeatherInfo.
    public static func info(cityName: String, completion: @escaping APICompletion<WeatherInfo>) {
        func getCityCodeList() -> [String: String] {
            let url = Bundle(for: self).url(forResource: "CityCode", withExtension: "plist")!
            return NSDictionary(contentsOf: url) as! [String: String]
        }
        guard let cityCode = cityCodeCache[cityName] ?? getCityCodeList()[cityName] else {
            return
        }
        cityCodeCache[cityName] = cityCode
        weatherProvider.request(.weather(cityCode: cityCode), completion: wrapInThread(completion))
    }
}
